package org.indi.graduatemanagement.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.indi.graduatemanagement.common.dto.LoginDto;
import org.indi.graduatemanagement.common.lang.Result;
import org.indi.graduatemanagement.entity.User;
import org.indi.graduatemanagement.service.UserService;
import org.indi.graduatemanagement.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("userName", loginDto.getUserName()));
        Assert.notNull(user, "用户不存在");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        user.setStatus(1);
        userService.updateById(user);
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        String[] permissionStr = user.getPermission().split(",");
        List<String> permission = new ArrayList<String>(Arrays.asList(permissionStr));

        return Result.successful(MapUtil.builder()
                .put("id", user.getId())
                .put("userName", user.getUserName())
                .put("roles",user.getRoles())
                .put("permission",permission)
                .map()
        );
    }

    @GetMapping("/loginCheck")
    public Result jwtCheck(@RequestParam(value="jwt") String jwt) {
        Claims claim = jwtUtils.getClaimByToken(jwt);
        if(claim != null && !jwtUtils.isTokenExpired(claim.getExpiration())){
            return Result.successful(claim);
        }
        return Result.successful("登录已过期或未登录");
    }


    @RequiresAuthentication
    @GetMapping("/logout/{userName}")
    public Result logout(@PathVariable("userName") String userName) {
        User user = userService.getOne(new QueryWrapper<User>().eq("userName", userName));
        user.setStatus(0);
        userService.updateById(user);
        SecurityUtils.getSubject().logout();
        return Result.successful(null);
    }
}
